import cutils from '../../js/common/core-utils.js';

$(function() {
	$("#q-icon").keyup(function() {
		var icon = $("#q-icon").val();
		$("#q-icon-i").attr("class", "fa " + (icon == "" ? "fa fa-paper-plane-o" : icon));
	});
	initData();
});

self.initData = function() {
	$(".only-for-menu").show();

	layui.form.on('radio(type)', function(obj) {
		if ($(obj.elem).val() == 0) {
			$(".only-for-menu").show();
		} else {
			$(".only-for-menu").hide();
		}
	});

	var vars = cutils.getUrlVars();
	var functionPId = vars["functionPId"];

	if (cutils.isEmpty(functionPId)) {
		return;
	}

	$.ajax({
		type: "get",
		url: "/" + cutils.webApp + "/function/" + functionPId + "?_time=" + cutils.now(),
		data: $('#q-data-form').serialize(),
		dataType: 'json',
		success: function(result) {
			if (cutils.notEquals(result.status, 200)) {
				layer.msg(result.message, { icon: 7 });
				return;
			}
			$("#q-p-id").val(result.data.functionId);
			$("#q-p-name").val(result.data.name);
		}
	});
}

self.doSubmitHandler = function(layerFromWin, pageFromWindow) {
	var functionName = $("#q-name").val();
	var order = $("#q-order").val();

	if (cutils.isEmpty(functionName)) {
		layer.tips('请输入功能名称', '#q-name', {
			tips: 1
		});
		return;
	}

	if (cutils.isNotEmpty(order) && cutils.isNotPositiveInteger(order)) {
		layer.tips('序号只能是正整数', '#q-order', {
			tips: 1
		});
		return;
	}

	$.ajax({
		type: "POST",
		url: "/" + cutils.webApp + "/function?_time=" + cutils.now(),
		data: $('#q-data-form').serialize(),
		dataType: 'json',
		success: function(result) {
			if (cutils.equals(result.status, 200)) {
				layerFromWin.layer.msg(result.message, { icon: 1, time: 1000 });
				var indexFrame = layerFromWin.layer.getFrameIndex(window.name);
				layerFromWin.layer.close(indexFrame);
				pageFromWindow.doSearch();
				return;
			}
			layerFromWin.layer.msg(result.message, { icon: 7 });
		}
	});
}

self.doSelectFunction = function() {
	top.layer.open({
		type: 2,
		title: '选择功能',
		area: ['320px', '450px'],
		shade: 0.01,
		maxmin: true,
		shadeClose: true,
		content: "/" + cutils.webApp + "/views/function/select.html?singleSelect=true&functionId=" + $("#q-p-id").val() + "&_time=" + cutils.now(),
		btn: ['<i class="fa fa-check" style="color: inherit;"></i>确定', '<i class="fa fa-eraser" style="color: inherit;"></i>清除', '<i class="fa fa-remove" style="color: inherit;"></i>取消'],
		yes: function(index, layero) {
			var iframeWin = layero.find('iframe')[0];
			var data = iframeWin.contentWindow.getChecked();

			if (cutils.isEmpty(data)) {
				iframeWin.contentWindow.layer.msg("请选择上级功能", { icon: 7 });
				return;
			}

			$("#q-p-id").val(data.functionId);
			$("#q-p-name").val(data.name);
			top.layer.close(index);
		},
		btn2: function(index, layero) {
			$("#q-p-id").val("");
			$("#q-p-name").val("");
			top.layer.close(index);

		}, btn3: function(index, layero) {
			top.layer.close(index);
		},
		cancel: function(index) {
			top.layer.close(index);
		}
	});
}